package com.bite.springtrans.demos.controller;

import com.bite.springtrans.demos.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@Slf4j
@RestController
@RequestMapping("/trans")
public class TransController {
    @Autowired
    private UserService userService;


    //注解实现事务
    @Transactional
    @RequestMapping("/registry")
    public String registry(String userName,String password) {
        //用户注册
        //开启事务
        Integer result = userService.registryUser(userName, password);
        log.info("用户插入成功,result : " + result);
        return "注册成功";
    }

    //注解实现事务
    @Transactional
    @RequestMapping("/registry2")
    public String registry2(String userName,String password) {
        //用户注册
        //开启事务
        Integer result = userService.registryUser(userName, password);
        log.info("用户插入成功,result : " + result);
        int a = 10/0;
        return "注册成功";
    }


    //演示捕获异常情况
    @Transactional
    @RequestMapping("/registry3")
    public String registry3(String userName,String password) {
        //用户注册
        //开启事务
        Integer result = userService.registryUser(userName, password);
        log.info("用户插入成功,result : " + result);
        try {
            int a = 10/0;
        } catch (Exception e) {
            log.info("程序出错");
            throw new RuntimeException();   //IOException 除外
        }

        return "注册成功";
    }


    //自定义异常
    @Transactional(rollbackFor = {Exception.class,Error.class})
    @RequestMapping("/registry4")
    public String registry4(String userName,String password) {
        //用户注册
        //开启事务
        Integer result = userService.registryUser(userName, password);
        log.info("用户插入成功,result : " + result);
        try {
            int a = 10/0;
        } catch (Exception e) {
            log.info("程序出错");
            throw new RuntimeException();   //IOException 除外
        }

        return "注册成功";
    }
}
